import router from '@/router'
import { useUserStore } from '@/stores'
import axios from 'axios'
import type { Method } from 'axios'
import { showToast } from 'vant'

const baseURL = 'https://consult-api.itheima.net/'

const instance = axios.create({
  baseURL: baseURL,
  timeout: 10000
})

//请求拦截器
instance.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    const token = userStore.user?.token
    console.log(token)
    if (token) {
      //注入token
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (err) => Promise.reject(err)
)

//响应拦截器
instance.interceptors.response.use(
  (response) => {
    //判断后端的code是否为10000
    if (response.data.code !== 10000) {
      //请求出错
      //提示用户
      showToast(response.data.message || '系统出错')
    }
    return response.data
  },
  (err) => {
    if (err.response.status === 401) {
      const store = useUserStore()
      //清空用户信息
      store.delUser()
      router.push('/login')
    }
    return Promise.reject(err)
  }
)

type Data<T> = {
  code: number
  message: string
  data: T
}

//基于instance封装一个request请求
const request = <T>(
  url: string,
  method: Method = 'get',
  submitData?: object
) => {
  //为了继承泛型
  return instance.request<T, Data<T>>({
    url,
    method,
    [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData
  })
}
//调用接口requset的时候，会把当前接口后端返回的数据的ts类型作为泛型传入

//baseURL其他地方可能会用到
export { request, baseURL }
